﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using cs499.Database;

namespace cs499.Admin
{
    public partial class ListUsers : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["action"] != null)
            {
                if (Request.QueryString["action"] != "")
                {
                    ListActionMessage.Text = Request.QueryString["action"] + "<br />";
                }
            }
            else
            {
                ListActionMessage.Text = "";
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            LinkButton adminMenuButton = (LinkButton)Master.FindControl("LoginView").FindControl("AdminMenuButton");
            adminMenuButton.CssClass = "selected";
        }

        protected void Page_PreRenderComplete(object sender, EventArgs e)
        {
            if (Master.DepartmentSelection.SelectedIndex != -1)
            {
                DepartmentLabel.Text = Master.DepartmentSelection.SelectedValue;
            }
            else
            {
                DepartmentLabel.Text = "(No departments defined)";
            }
        }

        protected void ExportUserButton_Click(object sender, EventArgs e)
        {
            System.Text.StringBuilder exportFile = new System.Text.StringBuilder();

            //add header info
            exportFile.AppendLine("#FIELD INFO");
            exportFile.AppendLine("#Email: The email will act as the user name(eg person@domain.com)");
            exportFile.AppendLine("");

            //add example lines
            exportFile.AppendLine("#EXAMPLES");
            exportFile.AppendLine("#xyz0001@uah.edu");
            exportFile.AppendLine("#abc0001@uah.edu");
            exportFile.AppendLine("");
            exportFile.AppendLine("");

            //add field name line
            exportFile.AppendLine("#Email");

            int currentDepartmentId = (int)HttpContext.Current.Session["CurrentDepartmentId"];
            foreach (MembershipUser user in ListOfDepartment.GetUsersInDepartment(currentDepartmentId))
            {
                exportFile.AppendLine(user.UserName);
            }

            Response.ContentType = @"application/x-msdownload";
            Response.AppendHeader("content-disposition", "attachment; filename=Users.csv");

            Response.Write(exportFile.ToString());
            Response.Flush();
            Response.End();
        }
    }
}